// mcp-handler.js - MCP请求处理逻辑
const { MCP_TOOLS } = require('./mcp-tools.js');
const { writeDebugLog, writeErrorLog, writeRequestLog } = require('./logging-utils.js');

/**
 * 处理MCP请求
 * @param {Object} request - MCP请求对象
 * @returns {Promise<Object>} - MCP响应对象
 */
async function handleMCPRequest(request) {
    try {
        const { method, params, id } = request;

        writeDebugLog('Processing MCP request', 'DEBUG', { method, id, params });
        writeRequestLog('REQUEST', request);

        let result;
        switch (method) {
            case 'initialize':
                writeDebugLog('Handling initialize request', 'DEBUG');
                result = await handleInitialize(request);
                break;

            case 'tools/list':
                writeDebugLog('Handling tools/list request', 'DEBUG');
                result = await handleToolsList();
                break;

            case 'tools/call':
                writeDebugLog('Handling tools/call request', 'DEBUG', { toolName: params?.name });
                result = await handleToolCall(params);
                break;

            default:
                writeDebugLog('Unknown method requested', 'WARN', { method, id });
                result = {
                    jsonrpc: "2.0",
                    id: request.id,
                    error: {
                        code: -32603,
                        message: `Unknown method: ${method}`
                    }
                };
        }

        writeRequestLog('RESPONSE', result);
        writeDebugLog('MCP request processed successfully', 'DEBUG', { method, id });
        return result;

    } catch (error) {
        writeErrorLog('Error in handleMCPRequest', error, {
            request,
            method: request?.method,
            id: request?.id
        });

        return {
            jsonrpc: "2.0",
            id: request?.id,
            error: {
                code: -32603,
                message: `Internal error: ${error.message}`,
                data: { stack: error.stack }
            }
        };
    }
}

/**
 * 处理initialize请求
 * @param {Object} request - MCP请求对象
 * @returns {Object} - MCP响应对象
 */
function handleInitialize(request) {
    return {
        jsonrpc: "2.0",
        id: request.id,
        result: {
            protocolVersion: "2024-11-05",
            capabilities: {
                tools: {}
            },
            serverInfo: {
                name: "vision-analyzer-mcp",
                version: "1.0.0"
            }
        }
    };
}

/**
 * 处理tools/list请求
 * @returns {Object} - MCP响应对象
 */
function handleToolsList() {
    const tools = MCP_TOOLS.map(tool => ({
        name: tool.name,
        description: tool.description,
        inputSchema: tool.inputSchema
    }));

    return {
        jsonrpc: "2.0",
        id: 2,
        result: {
            tools
        }
    };
}

/**
 * 处理tools/call请求
 * @param {Object} params - 工具调用参数
 * @returns {Promise<Object>} - MCP响应对象
 */
async function handleToolCall(params) {
    const { name, arguments: args } = params;

    const tool = MCP_TOOLS.find(t => t.name === name);
    if (!tool) {
        return {
            jsonrpc: "2.0",
            id: 3,
            result: {
                content: [{ type: 'text', text: `错误: Unknown tool: ${name}` }],
                isError: true
            }
        };
    }

    try {
        const result = await tool.handler(args);
        return {
            jsonrpc: "2.0",
            id: 3,
            result
        };
    } catch (error) {
        return {
            jsonrpc: "2.0",
            id: 3,
            result: {
                content: [{ type: 'text', text: `错误: ${error.message}` }],
                isError: true
            }
        };
    }
}

/**
 * 注册MCP工具到服务器
 * @param {Object} server - MCP服务器实例
 */
function registerTools(server) {
    try {
        writeDebugLog('Starting tool registration process', 'INFO', {
            totalTools: MCP_TOOLS.length,
            toolNames: MCP_TOOLS.map(t => t.name)
        });

        MCP_TOOLS.forEach((tool, index) => {
            try {
                writeDebugLog(`Registering tool ${index + 1}/${MCP_TOOLS.length}: ${tool.name}`, 'DEBUG', {
                    toolName: tool.name,
                    description: tool.description,
                    inputSchema: tool.inputSchema,
                    hasHandler: typeof tool.handler === 'function'
                });

                // 验证inputSchema格式
                if (tool.inputSchema) {
                    writeDebugLog(`Validating inputSchema for ${tool.name}`, 'DEBUG', {
                        schemaType: typeof tool.inputSchema,
                        hasType: !!tool.inputSchema.type,
                        hasProperties: !!tool.inputSchema.properties,
                        hasRequired: !!tool.inputSchema.required,
                        schemaKeys: Object.keys(tool.inputSchema)
                    });
                }

                try {
                    // 创建一个包装的handler来捕获深层错误
                    const wrappedHandler = async (args) => {
                        try {
                            writeDebugLog(`Tool ${tool.name} called with args`, 'DEBUG', {
                                argsCount: args ? Object.keys(args).length : 0,
                                argsKeys: args ? Object.keys(args) : []
                            });

                            const result = await tool.handler(args);

                            writeDebugLog(`Tool ${tool.name} completed successfully`, 'DEBUG', {
                                resultType: typeof result,
                                hasContent: result && result.content
                            });

                            return result;
                        } catch (handlerError) {
                            writeErrorLog(`Handler error in tool ${tool.name}`, handlerError, {
                                args,
                                toolName: tool.name,
                                handlerType: typeof tool.handler
                            });
                            throw handlerError;
                        }
                    };

                    server.registerTool(tool.name, {
                        description: tool.description,
                        inputSchema: tool.inputSchema
                    }, wrappedHandler);

                    writeDebugLog(`Successfully registered tool: ${tool.name}`, 'INFO');

                } catch (registerError) {
                    writeErrorLog(`Failed to register tool: ${tool.name} during server.registerTool call`, registerError, {
                        toolName: tool.name,
                        inputSchema: tool.inputSchema
                    });
                    throw registerError;
                }

            } catch (toolError) {
                writeErrorLog(`Failed to register tool: ${tool.name}`, toolError, {
                    toolName: tool.name,
                    toolIndex: index,
                    inputSchema: tool.inputSchema
                });
                // 继续注册其他工具，不因为一个失败而停止
            }
        });

        writeDebugLog('Tool registration process completed', 'INFO', {
            successfulRegistrations: MCP_TOOLS.length
        });

    } catch (error) {
        writeErrorLog('Critical error in registerTools', error, {
            totalTools: MCP_TOOLS.length,
            mcpSdkVersion: require('@modelcontextprotocol/sdk/package.json').version
        });
        throw error; // 重新抛出错误，让上层处理
    }
}

module.exports = {
    handleMCPRequest,
    handleInitialize,
    handleToolsList,
    handleToolCall,
    registerTools
};